<script setup>
import { onMounted, ref, watch } from 'vue'
import SetFormula from "@/views/SystemManagement/FormulaManagement/components/setFormula.vue";
import { delFormulaApi, getFormulaApi, computeFormulaApi } from "@/api/formula.js";
import { useCompanyStore } from "@/stores/company.js";
import dayjs from 'dayjs';

// 获取 companyId
const companyStore = useCompanyStore();
const companyId = companyStore.currentCompany.id;

const data = ref([])
const loading = ref(false)

// 获取公式
const getFormula = async (company_id = companyId) => {
  loading.value = true
  try {
    const res = await getFormulaApi(company_id)
    data.value = res.data
  } catch (error) {
    console.error('Error getting formula:', error)
    ElNotification({
      title: '错误',
      type: 'error',
      message: '获取公式失败，请稍后再试'
    })
  } finally {
    loading.value = false
  }
}
watch(() => companyStore.currentCompany, () => {
  let companyId = companyStore.currentCompany.id;
  getFormula(companyId)
})

// 测试公式相关
const testDialogVisible = ref(false);
const currentFormula = ref(null);
const testForm = ref({
  startTime: dayjs().subtract(3, 'day').valueOf(),
  endTime: dayjs().subtract(1, 'day').startOf('day').valueOf()
});
const testResult = ref(null);
const computing = ref(false);

const testFormula = (row) => {
  currentFormula.value = row;
  testDialogVisible.value = true;
  testResult.value = null;
};

const computeFormula = async () => {
  if (!testForm.value.startTime || !testForm.value.endTime) {
    ElMessage.warning('请选择开始和结束时间');
    return;
  }
  computing.value = true;
  try {
    const params = {
      id: currentFormula.value.id,
      start_time: new Date(testForm.value.startTime).getTime(),
      end_time: new Date(testForm.value.endTime).getTime()
    };

    const res = await computeFormulaApi(params);
    if (res.code === 200) {
      testResult.value = res.data;
      ElMessage.success('计算成功');
    } else {
      ElMessage.error(res.message || '计算失败');
    }
  } catch (error) {
    console.error('Error computing formula:', error);
    ElMessage.error('计算失败，请稍后再试');
  } finally {
    computing.value = false;
  }
};

onMounted(() => {
  getFormula()
});

// 添加公式
const formulaAdd = ref()
const addFormula = () => {
  formulaAdd.value.open()
}

// 编辑公式
const editFormula = (row) => {
  formulaAdd.value.open(row)
};

// 删除公式
const deleteFormula = async (row) => {
  const delParam = {
    id: String(row.id)  // 将 id 转换为字符串
  };

  try {
    // 弹出确认框
    await ElMessageBox.confirm(
      '此操作将永久删除该公式, 是否继续?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 如果用户点击了“确定”，则继续执行删除逻辑
    const res = await delFormulaApi(delParam);
    if (res.code === 200) {
      // 从 data 列表中移除被删除的项
      data.value = data.value.filter(item => item.id !== row.id);

      // 提示用户删除成功
      ElMessage({
        message: '删除成功',
        type: 'success',
      });
    } else {
      // 如果响应码不是 200，提示用户删除失败
      ElMessage({
        message: `删除失败: ${res.message || '未知错误'}`,
        type: 'error',
      });
    }
  } catch (error) {
    // 判断是否为取消操作
    if (error !== 'cancel') {
      // 捕获请求失败的错误，提示用户
      console.error('Error deleting formula:', error);
      ElMessage({
        message: '删除失败，请稍后再试',
        type: 'error',
      });
    } else {
      // 用户取消删除，不需要任何操作
      console.log('用户取消删除操作');
    }
  }
};

const disableFutureDate = (time) => {
  // 获取当前日期的开始时间（0点0分0秒）
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() >= today.getTime();
};
</script>

<template>
  <div class="page-title" style="display: flex;justify-content: space-between; align-items: center;">
    公式管理
    <el-button style="margin-left: 16px;" type="primary" icon="plus" @click="addFormula">添加公式</el-button>
  </div>

  <div class="formula-management">
    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="data" border stripe class="custom-table">
      <el-table-column prop="name" label="公式名称" align="center" width="200" />
      <el-table-column prop="usage" label="使用标识" align="center" width="200" />
      <el-table-column prop="formula" label="公式内容" align="center" />
      <el-table-column label="操作" align="center" width="280">
        <template #default="scope">
          <el-button @click="editFormula(scope.row)" type="primary" size="small" class="action-button">
            编辑
          </el-button>
          <el-button @click="testFormula(scope.row)" type="success" size="small" class="action-button">
            测试
          </el-button>
          <el-button @click="deleteFormula(scope.row)" type="danger" size="small" class="action-button">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑公式组件 -->
    <set-formula ref="formulaAdd" @update-formula="getFormula"></set-formula>

    <!-- 测试公式弹窗 -->
    <el-drawer v-model="testDialogVisible" title="测试公式">
      <div class="test-formula-container">
        <div class="formula-info">
          <h3>公式信息</h3>
          <p><strong>公式名称：</strong>{{ currentFormula?.name }}</p>
          <p><strong>公式内容：</strong>{{ currentFormula?.formula }}</p>
        </div>

        <div class="test-parameters">
          <h3>测试参数</h3>
          <el-form :model="testForm" label-width="120px">
            <el-form-item label="开始时间">
              <el-date-picker v-model="testForm.startTime" type="datetime" placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm:ss" :disabledDate="disableFutureDate" />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker v-model="testForm.endTime" type="datetime" placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm:ss" :disabledDate="disableFutureDate" />
            </el-form-item>
          </el-form>
        </div>

        <div v-if="testResult != null" class="test-result">
          <h3>计算结果</h3>
          <el-alert :title="`计算结果: ${testResult}`" type="success" :closable="false" show-icon />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="testDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="computeFormula" :loading="computing">
            {{ computing ? '计算中...' : '计算' }}
          </el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped>
.formula-management {
  padding: 20px;
  border-radius: 8px;
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.el-table th {
  font-weight: 500;
  text-align: center;
}

.el-table td {
  text-align: center;
}

.action-button {
  margin-right: 10px;
}

.action-button:last-child {
  margin-right: 0;
}

.el-table__empty-text {
  font-size: 14px;
}

.test-formula-container {
  padding: 20px;
}

.formula-info {
  margin-bottom: 24px;
}

.formula-info h3,
.test-parameters h3,
.test-result h3 {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.formula-info p {
  margin: 8px 0;
  line-height: 1.5;
}

.test-parameters {
  margin-bottom: 24px;
}

.test-result {
  margin-top: 24px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.action-button {
  margin: 0 4px;
}

.el-date-picker {
  width: 100%;
}
</style>
